package com.gitee.gen.controller;

import com.gitee.gen.common.Action;
import com.gitee.gen.common.GeneratorParam;
import com.gitee.gen.common.Result;
import com.gitee.gen.entity.DatasourceConfig;
import com.gitee.gen.gen.CodeFile;
import com.gitee.gen.gen.GeneratorConfig;
import com.gitee.gen.service.DatasourceConfigService;
import com.gitee.gen.service.GeneratorService;
import com.gitee.gen.common.MemCache;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author tanghc
 */
@Controller
@Mapping("generate")
public class GeneratorController {

    @Inject
    private DatasourceConfigService datasourceConfigService;

    @Inject
    private GeneratorService generatorService;


private final MemCache<String, List<CodeFile>> codeCache =
        new MemCache<>(100, 10);   // 最大 100 条，10 分钟过期



    /**
     * 生成代码
     *
     * @param generatorParam 生成参数
     * @return 返回代码内容
     */
    @Mapping("/code")
    public Result code(GeneratorParam generatorParam) {
        int datasourceConfigId = generatorParam.getDatasourceConfigId();
        DatasourceConfig datasourceConfig = datasourceConfigService.getById(datasourceConfigId);
        GeneratorConfig generatorConfig = GeneratorConfig.build(datasourceConfig);

        List<CodeFile> generate = generatorService.generate(generatorParam, generatorConfig);

        String key = generatorParam.getDatasourceConfigId() + "_" + String.join(",", generatorParam.getTableNames());
        codeCache.put(key, generate);
        return Action.ok(generate);
    }
    /**
     * 导出文件到指定路径
     *
     * @param generatorParam 生成参数
     * @return 返回代码内容
     */
    @Mapping("/export")
    public Result export(GeneratorParam generatorParam) throws IOException {
        System.out.println(generatorParam);
        String key = generatorParam.getDatasourceConfigId() + "_" + String.join(",", generatorParam.getTableNames());
        System.out.println(key);
        List<CodeFile> generate = null;
        List<CodeFile> cacheFiles = codeCache.get(key);
        if (cacheFiles == null) {
            // 缓存中没有找到代码
            System.out.println("缓存中没有找到代码");
            int datasourceConfigId = generatorParam.getDatasourceConfigId();
            DatasourceConfig datasourceConfig = datasourceConfigService.getById(datasourceConfigId);
            GeneratorConfig generatorConfig = GeneratorConfig.build(datasourceConfig);
             generate = generatorService.generate(generatorParam, generatorConfig);
        }else {
            generate = cacheFiles;
        }


        System.out.println("导出代码文件：" + generate);
        String result = generatorService.export(generate, generatorParam);

        System.out.println(result);
        return Action.ok(result);

    }


}
